package handler

import (
	"github.com/gin-gonic/gin"
	"map-master/cache"
	"map-master/moderl"
	"map-master/pkg"
	"time"
)

func Loge(c *gin.Context) {
	user := c.PostForm("user")
	password := c.PostForm("password")

	if user == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不可为空",
		})
		return
	}

	redis_key := "loge_id" + user
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		})
		return
	}

	////用户是否存在
	var lo moderl.Loge
	err := moderl.DB.Where("user = ?", user).Find(&lo).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if pkg.Md5(password) != lo.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount >= 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误成功3次,账号已封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
